#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "cJSON.h"
#include "Transer.h"

using namespace std;

void send_data(char *data);

int main()
{
    int server_fd, client_fd;
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_addr_len;
    char buf[1024];

    // create a TCP socket
    server_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (server_fd < 0) {
        cerr << "Failed to create socket\n";
        return -1;
    }

    // bind to a specific IP address and port
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr("192.168.1.231"); // bind to a specific IP address
    server_addr.sin_port = htons(/*12345*/65300); // use port in USR-TCP232-304 <Serial Port>
//    client_addr.sin_addr.s_addr = inet_addr("192.168.1.230");
//    client_addr.sin_port = htons(/*12345*/65300);
    client_addr.sin_addr.s_addr = inet_addr("192.168.1.202");
    client_addr.sin_port = htons(65300);
    if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        cerr << "Failed to bind to port\n";
        return -1;
    }

    // listen for incoming connections
    if (listen(server_fd, 5) < 0) {
        cerr << "Failed to listen for connections\n";
        return -1;
    }

    cout << "Waiting for connections...\n";

    while (1) {
        // accept a new connection
        client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_len);
        if (client_fd < 0) {
            cerr << "Failed to accept connection\n";
            continue;
        }

        cout << "Accepted connection from " << inet_ntoa(client_addr.sin_addr) << "\n";

        while (1) {
            // read data from the client
            int n = read(client_fd, buf, sizeof(buf)-1);
            if (n < 0) {
                cerr << "Failed to read data from client\n";
                break;
            } else if (n == 0) {
                cout << "Client closed the connection\n";
                break;
            } else {
                buf[n] = '\0';
                cout << "Received data: " << buf << "\n";

                // do something with the JSON data here...
                send_data(buf);
            }
        }

        close(client_fd);
        cout << "Closed connection with " << inet_ntoa(client_addr.sin_addr) << "\n";
    }

    close(server_fd);

    return 0;
}

void send_data(char *data){
    cout<<"below is data of read form collect:"<<endl;
    cout<<data<<endl;
    //模拟令牌
    cJSON *token=NULL;
    token=cJSON_CreateObject();
    cJSON_AddNumberToObject(token,"code",5);
    cJSON_AddStringToObject(token,"name","name");
    cJSON_AddStringToObject(token,"password","password");
    char *token_buf_json=NULL;
    token_buf_json= cJSON_Print(token);
    Transer t(token_buf_json,9090);
    //t.deal(data);
    cout<<"below is data after Transer"<<endl;
    cout<<t.deal(data)<<endl;
}